/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.ins.web;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.Collections3;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.ins.entity.InsField;
import com.thinkgem.jeesite.modules.ins.entity.InsTable;
import com.thinkgem.jeesite.modules.ins.entity.InsTableTemplate;
import com.thinkgem.jeesite.modules.ins.entity.InsTableUser;
import com.thinkgem.jeesite.modules.ins.service.InsFieldService;
import com.thinkgem.jeesite.modules.ins.service.InsTableService;
import com.thinkgem.jeesite.modules.ins.service.InsTableTemplateService;
import com.thinkgem.jeesite.modules.ins.service.InsTableUserService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 检验报告书-数据表Controller
 * @author fanqinglong
 * @version 2017-11-21
 */
@Controller
@RequestMapping(value = "${adminPath}/ins/insTable")
public class InsTableController extends BaseController {

	@Autowired
	private InsTableService insTableService;
	@Autowired
	private InsTableTemplateService insTableTemplateService;
	@Autowired
	private InsFieldService insFieldService;
	@Autowired
	private InsTableUserService insTableUserService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
	
	@ModelAttribute
	public InsTable get(@RequestParam(required=false) String id) {
		InsTable entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = insTableService.get(id);
		}
		if (entity == null){
			entity = new InsTable();
		}
		return entity;
	}
	
	@RequiresPermissions("ins:insTable:view")
	@RequestMapping(value = "export")
	@ResponseBody
	public String export(InsTable insTable,HttpServletRequest request,HttpServletResponse response){
		String url = insTableService.export(insTable, request);
		if (url.indexOf("error:")>-1) {
			return url;
		}
		File file = new File(url);
		return FileUtils.downFile(file, request, response);
	}
	
	/**
	 * 人员分配 -- 打开人员分配对话框
	 * @param insTable
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ins:insTable:view")
	@RequestMapping(value = "usertotable")
	public String selectUserToTable(InsTable insTable,Model model) {
		List<User> userList = systemService.getByTableId(insTable.getId());
		model.addAttribute("insTable", insTable);
		model.addAttribute("userList", userList);
		model.addAttribute("selectIds", Collections3.extractToString(userList, "name", ","));
		model.addAttribute("officeList", officeService.findAll());
		return "modules/ins/selectUserToTable";
	}
	/**
	 * 设置需要发送邮件的人员
	 * @param insTable
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "setReceiveIds")
	public String setReceiveIds(HttpServletRequest request,InsTable insTable,Model model) {
		String ids = request.getParameter("ids");
		List<User> userList = new ArrayList<>();
		if (!StringUtils.isEmpty(ids)) {
			String[] idArray = ids.split(",");
			if (idArray.length > 0) {
				userList = systemService.getByReceiveIds(idArray);
			}
		}
		model.addAttribute("userList", userList);
		model.addAttribute("selectIds", Collections3.extractToString(userList, "id", ","));
		model.addAttribute("officeList", officeService.findAll());
		return "modules/ins/setReceiveIds";
	}
	/**
	 * 打开数据限制输入框
	 * @return
	 */
	@RequiresPermissions("ins:insTable:view")
	@RequestMapping(value = "numberRange")
	public String numberRange(HttpServletRequest request,Model model){
		String numberFrom = request.getParameter("numberFrom");
		String numberTo = request.getParameter("numberTo");
		String enableNumberRange = request.getParameter("enableNumberRange");
		String digit = request.getParameter("digit");
		model.addAttribute("numberFrom", numberFrom);
		model.addAttribute("numberTo", numberTo);
		model.addAttribute("enableNumberRange", enableNumberRange);
		model.addAttribute("digit", digit);
		return "modules/ins/insNumberRange";
	}
	/**
	 * 人员分配
	 * @param role
	 * @param idsArr
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "assignTable")
	public String assignTable(InsTable insTable, String[] idsArr, RedirectAttributes redirectAttributes) {
		String msg = insTableService.assignUser(insTable, idsArr);
		addMessage(redirectAttributes, msg);
		return "redirect:" + adminPath + "/ins/insTable/toAssignView?id="+insTable.getId();
	}
	
	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "outTable")
	public String outTable(String userId, InsTable insTable, RedirectAttributes redirectAttributes){
		User user = systemService.getUser(userId);
		// 负责人不能被移除
		if (null != user && null != insTable && null != insTable.getCreateBy()) {
			if (user.getId().equals(insTable.getCreateBy().getId())) {
				addMessage(redirectAttributes, "创建人不能被移除！");
				return "redirect:" + adminPath + "/ins/insTable/toAssignView?id="+insTable.getId();
			}
		}
		Boolean flag = insTableService.outTable(insTable, user);
		if (!flag) {
			addMessage(redirectAttributes, "用户【" + user.getName() + "】从数据表【" + insTable.getName() + "】中移除失败！");
		}else {
			addMessage(redirectAttributes, "用户【" + user.getName() + "】从数据表【" + insTable.getName() + "】中移除成功！");
		}
		return "redirect:" + adminPath + "/ins/insTable/toAssignView?id="+insTable.getId();
	}
	
	@RequiresPermissions("ins:insTable:view")
	@RequestMapping(value = {"list", ""})
	public String list(InsTable insTable, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (!SecurityUtils.getSubject().isPermitted("ins:insTable:viewAll")) {
			insTable.getSqlMap().put("dsf", InsTableService.getDSF(UserUtils.getUser().getId(), "8"));
		}
		Page<InsTable> page = insTableService.findPage(new Page<InsTable>(request, response), insTable); 
		model.addAttribute("page", page);
		model.addAttribute("insTable", insTable);
		return "modules/ins/insTableList";
	}

	@RequiresPermissions("ins:insTable:view")
	@RequestMapping(value = "form")
	public String form(InsTable insTable, Model model) {
		InsField param = new InsField();
		param.setFrequently("1");
		List<InsField> list = insFieldService.findList(param);
		model.addAttribute("fieldList", list);
		model.addAttribute("insTable", insTable);
		//查询出可用的模板
		List<InsTableTemplate> templates = insTableTemplateService.findList(new InsTableTemplate());
		model.addAttribute("templates", templates);
		return "modules/ins/insTableForm";
	}

	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "save")
	public String save(InsTable insTable, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, insTable)){
			return form(insTable, model);
		}
		insTableService.save(insTable);
		addMessage(redirectAttributes, "保存数据表成功");
		return "redirect:"+Global.getAdminPath()+"/ins/insTable/?repage";
	}
	
	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "delete")
	public String delete(InsTable insTable,HttpServletRequest request, RedirectAttributes redirectAttributes) {
		insTableService.delete(insTable);
		addMessage(redirectAttributes, "删除数据表成功");
		return "redirect:"+Global.getAdminPath()+"/ins/insTable/?repage";
	}

	@RequiresPermissions("ins:insTable:bind")
	@RequestMapping(value = "bindTemplate")
	public String bindTemplate(InsTable insTable,RedirectAttributes redirectAttributes){
		try {
			insTableService.bindTemplate(insTable);
		} catch (Exception e) {
			addMessage(redirectAttributes, "绑定失败!");
			redirectAttributes.addAttribute("tableId", insTable.getId());
			return "redirect:"+Global.getAdminPath()+"/ins/insTemplate/bindList?repage";
		}
		addMessage(redirectAttributes, "绑定成功!");
		redirectAttributes.addAttribute("tableId", insTable.getId());
		return "redirect:"+Global.getAdminPath()+"/ins/insTemplate/bindList?repage";
	}
	
	@RequiresPermissions("ins:insTable:unbind")
	@RequestMapping(value = "unbindTemplate")
	public String unBindTemplate(InsTable insTable, RedirectAttributes redirectAttributes){
		insTableService.unBindTemplate(insTable);
		addMessage(redirectAttributes, "解绑成功");
		return "redirect:"+Global.getAdminPath()+"/ins/insTable/?repage";
	}
	
	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "getByName")
	@ResponseBody
	public String getByName(InsTable insTable){
		String result = "false";
		InsTable resultTable = insTableService.getByName(insTable);
		if (null == resultTable || resultTable.getId().equals(insTable.getId())) {
			result = "true";
		}
		return result;
	}
	
	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "toAssignView")
	public String toAssignView(InsTable insTable,Model model){
		InsTableUser param = new InsTableUser();
		param.setTable(insTable);
		List<InsTableUser> tableUsers = insTableUserService.findListForAuth(param);
		insTable.setInsTableUserList(tableUsers);
		model.addAttribute("insTable", insTable);
		return "modules/ins/insTableAssign";
	}
	
	@RequestMapping(value = "assignAuth")
	public String assignAuth(InsTable insTable, RedirectAttributes redirectAttributes) {
		insTableService.assignAuth(insTable);
		addMessage(redirectAttributes, "授权成功");
		return "redirect:"+Global.getAdminPath()+"/ins/insTable/?repage";
	}
	
	@RequiresPermissions("ins:insTable:edit")
	@RequestMapping(value = "getTemplate")
	@ResponseBody
	public InsTableTemplate getTemplate(HttpServletRequest request){
		String id = request.getParameter("templateId");
		InsTableTemplate tableTemplate = insTableTemplateService.get(id);
		return tableTemplate;
	}
}